/**
 * 
 */
package com.effectiv.req1.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.effectiv.req1.domain.Company;
import com.effectiv.req1.domain.Lov;
import com.effectiv.req1.domain.User;
import com.effectiv.req1.repository.CompanyRepository;
import com.effectiv.req1.repository.LovRepository;
import com.effectiv.req1.repository.UserRepository;


/**
 * @author Dhrubo
 * 
 */
@Controller
@Slf4j
public class RegistrationController {
	
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private CompanyRepository companyRepository;
	@Autowired
	private LovRepository lovRepository;
	
	@RequestMapping(value = "/registration")
	public final String showRegisterDisplay(Model model) {
		
		User user = new User();
		user.setCompany(new Company());
		
		model.addAttribute(user);


		return "registration";
	}
	
	@RequestMapping(value = "/registeruser", method = RequestMethod.POST)
	public final String register(@Valid User user, BindingResult result) {
		
		log.info("###### User - {}", user);
		
		if (!result.hasErrors()) {

			log.info("###### saving user - {}", user);
			
			Date timestamp = new Date();
			
			//save company
			
			Company company = user.getCompany();
			company.setCreatedDate(timestamp);
			companyRepository.save(company);
			
			//save user
			user.setCreatedDate(timestamp);
			user.setLastUpdatedDate(timestamp);
			
			//TODO - change this to generate random string with commons random string
			user.setPassword("salman");
			
			
			Lov role = lovRepository.findByName("ROLE_COMPANY_ADMIN");
			log.debug("Role = {}", role);
			
			List<Lov> roles = new ArrayList<Lov>();
			roles.add(role);
			
			user.setRoles(roles);
			
			userRepository.save(user);
			
			//TODO
			//send mail to be done later
			
		}	
		
		return "registration";
	}
	
}
